import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_wanandroid/common/api.dart';
import 'package:flutter_wanandroid/entity/user_entity.dart';
import 'package:flutter_wanandroid/httpUtils/http_util.dart';
import 'package:flutter_wanandroid/main.dart';
import 'package:flutter_wanandroid/res/colors.dart';
import 'package:flutter_wanandroid/utils/y_toast.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  GlobalKey<FormState> _key = GlobalKey();
  String? username, password, rePassword;
  bool visible = true;
  String btnText = "登录";
  bool autoValidate = false;
  String bottomText = "没有账号？注册";

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
          primaryColor: Theme.of(context).primaryColor,
          hintColor: Theme.of(context).hintColor,
          primaryColorDark: Theme.of(context).primaryColorDark),
      home: Container(
        decoration: BoxDecoration(
            gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Theme.of(context).hintColor,
            Theme.of(context).primaryColorDark
          ],
        )),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          body: getBodyView(),
        ),
      ),
    );
  }

  Widget getBodyView() {
    //可滑动布局，避免弹出键盘时会有溢出异常
    return ListView(
      children: [
        SizedBox(
          height: 80,
        ),
        Stack(
          alignment: Alignment.topCenter,
          children: [
            Container(
              margin: EdgeInsets.only(top: 50),
              padding: EdgeInsets.all(40),
              child: Card(
                color: Colors.white,
                elevation: 5,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(
                    Radius.circular(15),
                  ),
                ),
                child: Padding(
                  padding: EdgeInsets.all(20),
                  child: Form(
                    autovalidateMode: AutovalidateMode.onUserInteraction,
                    key: _key,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        TextFormField(
                          //键盘类型，即输入类型
                          keyboardType: TextInputType.number,
                          textInputAction: TextInputAction.next,
                          decoration: InputDecoration(
                            icon: Icon(Icons.person_outline),
                            labelText: "请输入账号",
                          ),
                          validator: validateUsername,
                          onSaved: (text) {
                            username = text;
                          },
                        ),
                        const SizedBox(
                          height: 20,
                        ),
                        TextFormField(
                          keyboardType: TextInputType.number,
                          textInputAction: TextInputAction.next,
                          decoration: InputDecoration(
                            icon: Icon(Icons.lock_outline),
                            labelText: "请输入密码",
                          ),
                          validator: validatePassword,
                          onSaved: (text) {
                            password = text;
                          },
                        ),
                        const SizedBox(
                          height: 20,
                        ),
                        Offstage(
                          offstage: visible,
                          child: TextFormField(
                            keyboardType: TextInputType.number,
                            textInputAction: TextInputAction.next,
                            decoration: InputDecoration(
                              icon: Icon(Icons.lock_outline),
                              labelText: "请确认密码",
                            ),
                            validator: validatePassword,
                            onSaved: (text) {
                              rePassword = text;
                            },
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ),
            ),
            Positioned(
                top: 40,
                left: MediaQuery.of(context).size.width / 2 - 35,
                child: Center(
                  child: Container(
                    width: 70,
                    height: 70,
                    decoration: const BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.white,
                      image: DecorationImage(
                        image: AssetImage("lib/res/images/ic_logo.png"),
                      ),
                      boxShadow: [
                        BoxShadow(
                          //左右、上下阴影的距离
                          offset: Offset(0, 0),
                          //阴影颜色
                          color: Colors.red,
                          //模糊距离
                          blurRadius: 8,
                          //不模糊距离
                          spreadRadius: 1,
                        ),
                      ],
                    ),
                  ),
                )),
            Positioned(
              bottom: 20,
              left: 130,
              right: 130,
              child: ElevatedButton(
                child: Container(
                  padding: const EdgeInsets.all(10),
                  child: Text(
                    btnText,
                    style: const TextStyle(color: Colors.white, fontSize: 20),
                  ),
                ),
                onPressed: () {
                  if (_key.currentState != null && _key.currentState!.validate()) {
                    _key.currentState!.save();
                    print("${username!}--$password**$rePassword");
                    doRequest();
                  } else {
                    setState(() {
                      autoValidate = true;
                    });
                  }
                },
              ),
            ),

          ],
        ),
        GestureDetector(
          child: Text(
            bottomText,
            style: const TextStyle(color: YColors.color_fff),
            textAlign: TextAlign.center,
          ),
          onTap: () {
            setState(() {
              if (visible) {
                btnText = "注册";
                visible = false;
                bottomText = "已有账号？登录";
              } else {
                btnText = "登陆";
                visible = true;
                bottomText = "没有账号？注册";
              }
            });
          },
        )
      ],
    );
  }

  String? validateUsername(String? value) {
    if (null == value) {
      return "账号不能为空";
    }
    if (value.isEmpty) {
      return "账号不能为空";
    }
    if (value.length < 6) {
      return "确认账号最少6位";
    }
    return null;
  }

  String? validatePassword(String? value) {
    if (null == value) {
      return "密码不能为空";
    }
    if (value.isEmpty) {
      return "密码不能为空";
    }
    if (value.length < 6) {
      return "确认密码最少6位";
    }
    return null;
  }

  Future doRequest() async {
    var data;
    if (visible) {
      data = {'username': username, 'password': password};
    } else {
      data = {'username': username, 'password': password, 'repassword': rePassword};
    }
    var response = await HttpUtil().post(visible ? Api.LOGIN : Api.REGISTER, data: data);
    print("登录结果接口返回结果: $response");
    Map<String ,dynamic> map = json.decode(response.toString());
    var userEntity = UserEntity.fromJson(map);
    if (userEntity.errorCode == 0) {
      YToast.show(visible ? '登陆成功' : '注册成功', context);
      //跳转并关闭当前页面
      // ignore: use_build_context_synchronously, unnecessary_null_comparison
      Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) => const MyHomePage(title: '')), (route) => route == null);
    } else {
      // ignore: use_build_context_synchronously
      YToast.show(userEntity.errorMsg ?? '', context);
    }

  }
}
